package com.bc.commoncore.util;

import javax.servlet.http.HttpServletRequest;

public class IPUtil {
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
			if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
				ip = SystemUtils.getLocalIp();
			}
		}
		// 多次反向代理后会有多个ip值，第一个ip才是真实ip
		if (ip != null && !ip.isEmpty()) {
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		return "";
	}

	// 获取真实IP，穿透CDN
	// public static String getIpAddr(HttpServletRequest request) {
	// String ip = request.getHeader("HTTP_VIA");
	// if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
	// return ip;
	// } else if (request.getHeader("REMOTE_ADDR") != null
	// && request.getHeader("REMOTE_ADDR").length() != 0
	// && !"unknown"
	// .equalsIgnoreCase(request.getHeader("REMOTE_ADDR"))) {
	// ip = request.getHeader("REMOTE_ADDR");
	// } else if (request.getHeader("HTTP_X_FORWARDED_FOR") != null
	// && request.getHeader("HTTP_X_FORWARDED_FOR").length() != 0
	// && !"unknown".equalsIgnoreCase(request
	// .getHeader("HTTP_X_FORWARDED_FOR"))) {
	// if (request.getHeader("HTTP_CLIENT_IP") != null
	// && request.getHeader("HTTP_CLIENT_IP").length() != 0
	// && !"unknown".equalsIgnoreCase(request
	// .getHeader("HTTP_CLIENT_IP"))) {
	// ip = request.getHeader("HTTP_CLIENT_IP");
	// } else {
	// if (request.getHeader("REMOTE_ADDR") != null
	// && request.getHeader("REMOTE_ADDR").length() != 0
	// && !"unknown".equalsIgnoreCase(request
	// .getHeader("REMOTE_ADDR"))) {
	// ip = request.getHeader("REMOTE_ADDR");
	// } else {
	// ip = "";
	// }
	// }
	// } else {
	// ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	// }
	// if (ip != null && !ip.isEmpty()) {
	// int index = ip.indexOf(",");
	// if (index != -1) {
	// return ip.substring(0, index);
	// } else {
	// return ip;
	// }
	// }
	// return "";
	// }

}
